package org.lv.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.lv.learning.entity.Account;
import org.lv.learning.mapper.AccountMapper;
import org.lv.learning.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 *
 */
@Service
public class AccountService implements IAccountService {

    @Autowired
    private AccountMapper accountMapper;

    /**
     * 扣减账户余额
     * @param userId
     * @param money
     * @return
     */
    @Override
    public Integer deduct(Long userId, BigDecimal money) {

        Account account = accountMapper.selectById(userId);

        if(ObjectUtil.isNull(account)){
            throw new RuntimeException("用户不存在");
        }


        LambdaUpdateWrapper<Account> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(Account::getUserId, userId);
        queryWrapper.gt(Account::getMoney, money);
        queryWrapper.setSql("money = money - " + money);
        int update = accountMapper.update(null, queryWrapper);

        if(update == 0){
            throw new RuntimeException("账户余额不足");
        }

        return update;
    }
}
